package com.xyht.sca_s.student_manage_system.modules.payment.wxpay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wechat.pay.java.core.notification.RequestParam;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.config.WxPayConfig;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.constant.OriginalTypeConstant;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.entity.*;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.service.WxService;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.util.AESUtil;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.util.WxPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Service
@Slf4j
public class WxServiceImpl implements WxService {
    @Resource
    private PlatformTransactionManager transactionManager; // 事务
    @Resource
    private WxPayUtil wxPayUtil;
    @Resource
    private AESUtil aesUtil;
    @Resource
    private WxPayConfigProperties wxPayConfigProperties;

    @Override
    public String wxPayCallback(CallbackBodyEntity entity, HttpServletRequest request, HttpServletResponse response) {
        log.info("-------------------------------支付回调进来------------------------");
        log.info("entity:{}", JSON.toJSONString(entity));

//        CallbackBodyResourceEntity body = new CallbackBodyResourceEntity();
//        BeanUtils.copyProperties(entity, body);
//        RequestParam requestParam = new RequestParam.Builder()
//                .signType(SIGN_TYPE)
//                .serialNumber(request.getParameter("Wechatpay-Serial"))
//                .signature(request.getParameter("Wechatpay-Signature"))
//                .timestamp(request.getParameter("Wechatpay-Timestamp"))
//                .nonce(request.getParameter("Wechatpay-Nonce"))
//                .body(JSONObject.toJSONString(body))
//                .build();
//        log.info("requestParam:{}", JSON.toJSONString(requestParam));
//        CallbackPayResourceEntity resourceEntity = wxPayUtil.checkNotificationSign(requestParam);
//        log.info("resourceEntity:{}", JSON.toJSONString(resourceEntity));

//        CallbackPayResourceEntity resourceEntity = new CallbackPayResourceEntity();
//        try {
//            CallbackAESResourceEntity aesResourceEntity = entity.getResource();
//            String resource = aesUtil.decryptToString(aesResourceEntity.getAssociated_data().getBytes(),
//                    aesResourceEntity.getNonce().getBytes(),
//                    aesResourceEntity.getCiphertext(),
//                    wxPayConfigProperties.getConfigs().get(0).getWX_API_V3_KEY());
//            log.debug("resource++++++++++++++++" + resource);
//            resourceEntity = JSONObject.parseObject(resource, CallbackPayResourceEntity.class);
//            if (resourceEntity == null) {
//                return null;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return dealWithPayment(resourceEntity, response);
        return "";
    }


    @Override
    public String wxPayCallbackOne(CallbackBodyEntity entity, HttpServletRequest request, HttpServletResponse response) {
        log.info("-------------------------------支付回调进来------------------------");
        log.info("entity:{}", JSON.toJSONString(entity));

//        CallbackBodyResourceEntity body = new CallbackBodyResourceEntity();
//        BeanUtils.copyProperties(entity, body);
//        RequestParam requestParam = new RequestParam.Builder()
//                .signType(SIGN_TYPE)
//                .serialNumber(request.getParameter("Wechatpay-Serial"))
//                .signature(request.getParameter("Wechatpay-Signature"))
//                .timestamp(request.getParameter("Wechatpay-Timestamp"))
//                .nonce(request.getParameter("Wechatpay-Nonce"))
//                .body(JSONObject.toJSONString(body))
//                .build();
//        log.info("requestParam:{}", JSON.toJSONString(requestParam));
//        CallbackPayResourceEntity resourceEntity = wxPayUtil.checkNotificationSign(requestParam);
//        log.info("resourceEntity:{}", JSON.toJSONString(resourceEntity));

        CallbackPayResourceEntity resourceEntity = new CallbackPayResourceEntity();
        try {
            CallbackAESResourceEntity aesResourceEntity = entity.getResource();
            String resource = aesUtil.decryptToString(aesResourceEntity.getAssociated_data().getBytes(),
                    aesResourceEntity.getNonce().getBytes(),
                    aesResourceEntity.getCiphertext(),
                    wxPayConfigProperties.getConfigs().get(0).getWX_API_V3_KEY());
            log.debug("resource++++++++++++++++" + resource);
            resourceEntity = JSONObject.parseObject(resource, CallbackPayResourceEntity.class);
            if (resourceEntity == null) {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        return dealWithPayment(resourceEntity, response);
        return "";
    }

    @Override
    public String wxPayCallbackTwo(CallbackBodyEntity entity, HttpServletRequest request, HttpServletResponse response) {
        log.info("-------------------------------支付回调进来------------------------");
        log.info("entity:{}", JSON.toJSONString(entity));

//        CallbackBodyResourceEntity body = new CallbackBodyResourceEntity();
//        BeanUtils.copyProperties(entity, body);
//        RequestParam requestParam = new RequestParam.Builder()
//                .signType(SIGN_TYPE)
//                .serialNumber(request.getParameter("Wechatpay-Serial"))
//                .signature(request.getParameter("Wechatpay-Signature"))
//                .timestamp(request.getParameter("Wechatpay-Timestamp"))
//                .nonce(request.getParameter("Wechatpay-Nonce"))
//                .body(JSONObject.toJSONString(body))
//                .build();
//        log.info("requestParam:{}", JSON.toJSONString(requestParam));
//        CallbackPayResourceEntity resourceEntity = wxPayUtil.checkNotificationSign(requestParam);
//        log.info("resourceEntity:{}", JSON.toJSONString(resourceEntity));

//        CallbackPayResourceEntity resourceEntity = new CallbackPayResourceEntity();
//        try {
//            CallbackAESResourceEntity aesResourceEntity = entity.getResource();
//            String resource = aesUtil.decryptToString(aesResourceEntity.getAssociated_data().getBytes(),
//                    aesResourceEntity.getNonce().getBytes(),
//                    aesResourceEntity.getCiphertext(),
//                    wxPayConfigProperties.getConfigs().get(1).getWX_API_V3_KEY());
//            log.debug("resource++++++++++++++++" + resource);
//            resourceEntity = JSONObject.parseObject(resource, CallbackPayResourceEntity.class);
//            if (resourceEntity == null) {
//                return null;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return dealWithPayment(resourceEntity, response);
        return "";
    }

    /**
     * 将以分为单位的金额(Integer)转换为以元为单位的金额(BigDecimal)
     *
     * @param moneyInCents 以分为单位的金额(Integer)
     * @return 以元为单位的金额(BigDecimal)
     */
    private BigDecimal centsToYuan(Integer moneyInCents) {
        // 将分转换为元, 需要除以100, 并将结果存储为BigDecimal类型
        return new BigDecimal(moneyInCents).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
    }

    /**
     * 失败应答
     */
    private String failResp(HttpServletResponse response) {
        response.setStatus(500);
        Map<String, String> map = new HashMap<>();
        map.put("code", "FAIL");
        map.put("message", "失败");
        return JSON.toJSONString(map);
    }

    /**
     * 成功应答
     */
    private String successResp(HttpServletResponse response) {
        response.setStatus(200);
        Map<String, String> map = new HashMap<>();
        map.put("code", "SUCCESS");
        map.put("message", "成功");
        return JSON.toJSONString(map);
    }

    /**
     * 手动回滚事务
     *
     * @param status 嵌套事务
     */
    private void rollback(TransactionStatus status) {
        // 手动回滚事务
        transactionManager.rollback(status);
        if (status.isNewTransaction() && !status.isCompleted()) {
            transactionManager.commit(status);
        }
    }
}
